@file:Suppress("DEPRECATION")

package com.starsea.book.ui.main

import android.content.Intent
import android.os.Bundle
import android.text.format.DateUtils
import android.view.MotionEvent
import android.widget.EditText
import androidx.activity.addCallback
import androidx.activity.viewModels
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.starsea.book.BuildConfig
import com.starsea.book.R
import com.starsea.book.base.VMBaseActivity
import com.starsea.book.constant.AppConst.appInfo
import com.starsea.book.constant.EventBus
import com.starsea.book.constant.PreferKey
import com.starsea.book.databinding.ActivityMainBinding
import com.starsea.book.help.AppWebDav
import com.starsea.book.help.book.BookHelp
import com.starsea.book.help.config.AppConfig
import com.starsea.book.help.config.LocalConfig
import com.starsea.book.help.config.ReadTipConfig
import com.starsea.book.help.coroutine.Coroutine
import com.starsea.book.help.storage.Backup
import com.starsea.book.lib.dialogs.alert
import com.starsea.book.service.BaseReadAloudService
import com.starsea.book.ui.adapter.MyFragmentStateAdapter
import com.starsea.book.ui.main.bookshelf.style1.books.BooksFragment
import com.starsea.book.ui.newpage.LoginActivity
import com.starsea.book.ui.newpage.utils.AppManager
import com.starsea.book.ui.widget.dialog.TextDialog
import com.starsea.book.utils.*
import com.starsea.book.utils.viewbindingdelegate.viewBinding
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine

/**
 * 主界面
 */
class MainActivity : VMBaseActivity<ActivityMainBinding, MainViewModel>() {

    override val binding by viewBinding(ActivityMainBinding::inflate)
    override val viewModel by viewModels<MainViewModel>()
    private val idExplore = 0
    private val idWelfare = 1
    private val idBookshelf = 2
    private val idMy = 3
    private var exitTime: Long = 0
    private var bookshelfReselected: Long = 0
    private var exploreReselected: Long = 0
    private var pagePosition = 0
    private var bottomMenuCount = 4
    private val realPositions = arrayOf(idExplore, idWelfare, idBookshelf, idMy)

    private lateinit var mFragmentAdapter: MyFragmentStateAdapter

    var mFragentList: MutableList<Fragment> = arrayListOf()

//    private val onUpBooksBadgeView by lazy {
//        binding.bottomNavigationView.addBadgeView(0)
//    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)

//        if (intent != null) {
//            var index = intent.getIntExtra("index", 0)
//            if (index == 3)
//                binding.viewPagerMain.setCurrentItem(realPositions.indexOf(idRss), false)
//
//        }

    }


    override fun onActivityCreated(savedInstanceState: Bundle?) {

//        AppManager.getInstance().killOtherExitThisActivity(MainActivity::class.java)

        AppManager.getInstance().killActivity(LoginActivity::class.java)

        initAdapter()

        setSelect(0)

        binding.rtvBookShelf.setOnClickListener {
            setSelect(0)
        }
        binding.rtvHome.setOnClickListener {
            setSelect(1)
        }

        binding.rtvWelfare.setOnClickListener {
            setSelect(2)
        }

        binding.rtvCategory.setOnClickListener {
            setSelect(3)
        }
        binding.rtvMine.setOnClickListener {
            setSelect(4)
        }

        lifecycleScope.launch {

        }

        ReadTipConfig.tipFooterRight = 8
        ReadTipConfig.tipFooterLeft = 6
        postEvent(EventBus.UP_CONFIG, true)

        onBackPressedDispatcher.addCallback(this) {
            if (pagePosition != 0) {
                binding.vpContent.currentItem = 0
                return@addCallback
            }
            (viewModel.getFragmentList()[binding.vpContent.currentItem] as? BooksFragment)?.let {
                if (it.isManage) {
                    it.exitManage()
                    return@addCallback
                }
            }
            if (System.currentTimeMillis() - exitTime > 2000) {
                toastOnUi(R.string.double_click_exit)
                exitTime = System.currentTimeMillis()
            } else {
                if (BaseReadAloudService.pause) {
                    finish()
                } else {
                    moveTaskToBack(true)
                }
            }
        }
    }


    private fun initAdapter() {
        mFragentList = viewModel.getFragmentList()
        mFragmentAdapter = MyFragmentStateAdapter(mFragentList, this)
        binding.vpContent.adapter = mFragmentAdapter
        binding.vpContent.isUserInputEnabled = false
        binding.vpContent.offscreenPageLimit = 4
    }

    private fun setSelect(index: Int) {
        binding.vpContent.setCurrentItem(index, false)
        binding.rtvBookShelf.isSelected = index == 0
        binding.rtvHome.isSelected = index == 1
        binding.rtvWelfare.isSelected = index == 2
        binding.rtvCategory.isSelected = index == 3
        binding.rtvMine.isSelected = index == 4
    }


    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (ev.action == MotionEvent.ACTION_DOWN) {
            currentFocus?.let {
                if (it is EditText) {
                    it.clearFocus()
                    it.hideSoftInput()
                }
            }
        }
        return try {
            super.dispatchTouchEvent(ev)
        } catch (e: IllegalArgumentException) {
            e.printStackTrace()
            false
        }
    }

    override fun onPostCreate(savedInstanceState: Bundle?) {
        super.onPostCreate(savedInstanceState)
        lifecycleScope.launch {
            //隐私协议
//            if (!privacyPolicy()) return@launch
            //版本更新
//            upVersion()
            //设置本地密码
//            setLocalPassword()
//            notifyAppCrash()
            //备份同步
            backupSync()
            //自动更新书籍
            val isAutoRefreshedBook = savedInstanceState?.getBoolean("isAutoRefreshedBook") ?: false
//            if (AppConfig.autoRefreshBook && !isAutoRefreshedBook) {
//                binding.viewPagerMain.postDelayed(1000) {
//                    viewModel.upAllBookToc()
//                }
//            }
//            binding.viewPagerMain.postDelayed(3000) {
//                viewModel.postLoad()
//            }
        }
    }
//
//    override fun onNavigationItemSelected(item: MenuItem): Boolean = binding.run {
//        when (item.itemId) {
//            R.id.menu_bookshelf ->
//                viewPagerMain.setCurrentItem(realPositions.indexOf(idBookshelf), false)
//
//            R.id.menu_discovery ->
//                viewPagerMain.setCurrentItem(realPositions.indexOf(idExplore), false)
//
//            R.id.menu_welfare ->
//                viewPagerMain.setCurrentItem(realPositions.indexOf(idWelfare), false)
//
//            R.id.menu_my_config ->
//                viewPagerMain.setCurrentItem(realPositions.indexOf(idMy), false)
//        }
//        return false
//    }

//    override fun onNavigationItemReselected(item: MenuItem) {
//        when (item.itemId) {
//            R.id.menu_bookshelf -> {
//                if (System.currentTimeMillis() - bookshelfReselected > 300) {
//                    bookshelfReselected = System.currentTimeMillis()
//                } else {
//                    (fragmentMap[getFragmentId(2)] as? BaseBookshelfFragment)?.gotoTop()
//                }
//            }
//
//            R.id.menu_discovery -> {
//                if (System.currentTimeMillis() - exploreReselected > 300) {
//                    exploreReselected = System.currentTimeMillis()
//                } else {
////                    (fragmentMap[1] as? HomeFragment)?.compressExplore()
//                    (fragmentMap[0] as? HomeFragment)?.compressExplore()
//                }
//            }
//        }
//    }

    /**
     * 用户隐私与协议
     */
    private suspend fun privacyPolicy(): Boolean = suspendCoroutine { block ->
        if (LocalConfig.privacyPolicyOk) {
            block.resume(true)
            return@suspendCoroutine
        }
        val privacyPolicy = String(assets.open("privacyPolicy.md").readBytes())
        alert(getString(R.string.privacy_policy), privacyPolicy) {
            noButton {
                finish()
                block.resume(false)
            }
            positiveButton(R.string.agree) {
                LocalConfig.privacyPolicyOk = true
                block.resume(true)
            }
            negativeButton(R.string.refuse) {
                finish()
                block.resume(false)
            }
        }
    }

    /**
     * 版本更新日志
     */
    private suspend fun upVersion() = suspendCoroutine { block ->
        if (LocalConfig.versionCode == appInfo.versionCode) {
            block.resume(null)
            return@suspendCoroutine
        }
        LocalConfig.versionCode = appInfo.versionCode
        if (LocalConfig.isFirstOpenApp) {
            val help = String(assets.open("help/appHelp.md").readBytes())
            val dialog = TextDialog(getString(R.string.help), help, TextDialog.Mode.MD)
            dialog.setOnDismissListener {
                block.resume(null)
            }
            showDialogFragment(dialog)
        } else if (!BuildConfig.DEBUG) {
            val log = String(assets.open("updateLog.md").readBytes())
            val dialog = TextDialog(getString(R.string.update_log), log, TextDialog.Mode.MD)
            dialog.setOnDismissListener {
                block.resume(null)
            }
            showDialogFragment(dialog)
        } else {
            block.resume(null)
        }
    }

    /**
     * 备份同步
     */
    private fun backupSync() {
        lifecycleScope.launch {
            val lastBackupFile =
                withContext(IO) { AppWebDav.lastBackUp().getOrNull() } ?: return@launch
            if (lastBackupFile.lastModify - LocalConfig.lastBackup > DateUtils.MINUTE_IN_MILLIS) {
                LocalConfig.lastBackup = lastBackupFile.lastModify
                alert(R.string.restore, R.string.webdav_after_local_restore_confirm) {
                    cancelButton()
                    okButton {
                        viewModel.restoreWebDav(lastBackupFile.displayName)
                    }
                }
            }
        }
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        if (AppConfig.autoRefreshBook) {
            outState.putBoolean("isAutoRefreshedBook", true)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        Coroutine.async {
            BookHelp.clearInvalidCache()
        }
        if (!BuildConfig.DEBUG) {
            Backup.autoBack(this)
        }
    }

    /**
     * 如果重启太快fragment不会重建,这里更新一下书架的排序
     */
    override fun recreate() {
//        (fragmentMap[getFragmentId(0)] as? BaseBookshelfFragment)?.run {
//            upSort()
//        }
        super.recreate()
    }

    override fun observeLiveBus() {
        viewModel.onUpBooksLiveData.observe(this) {

        }
        observeEvent<String>(EventBus.RECREATE) {
            recreate()
        }
//        observeEvent<Boolean>(EventBus.NOTIFY_MAIN) {
//            binding.apply {
//                upBottomMenu()
//                if (it) {
//                    vpContent.setCurrentItem(bottomMenuCount - 1, false)
//                }
//            }
//        }
        observeEvent<String>(PreferKey.threadCount) {
            viewModel.upPool()
        }


//        observeEvent<Int>(EventBus.NOTIFY_MAIN_CHANGE_INDEX) {
//            binding.apply {
//                upBottomMenu()
//                vpContent.setCurrentItem(it, false)
//            }
//        }


    }

//    private fun upBottomMenu() {
//        val showDiscovery = AppConfig.showDiscovery
//        binding.bottomNavigationView.menu.let { menu ->
//            menu.findItem(R.id.menu_discovery).isVisible = showDiscovery
////            menu.findItem(R.id.menu_rss).isVisible = showRss
//        }
//        var index = 0
//        if (showDiscovery) {
//            index++
//            realPositions[index] = idExplore
//        }
//
//        index++
//        realPositions[index] = idWelfare
//
//        index++
//        realPositions[index] = idMy
//        bottomMenuCount = index + 1
//        adapter.notifyDataSetChanged()
//    }
//
//    private fun upHomePage() {
//        when (AppConfig.defaultHomePage) {
//            "bookshelf" -> {}
//            "explore" -> if (AppConfig.showDiscovery) {
//                binding.viewPagerMain.setCurrentItem(realPositions.indexOf(idExplore), false)
//            }
//
//            "my" -> binding.viewPagerMain.setCurrentItem(realPositions.indexOf(idMy), false)
//        }
//    }

//    private fun getFragmentId(position: Int): Int {
//        val id = realPositions[position]
//
//        LogUtils.e(">>>> ", "position =${position} ")
//        LogUtils.e(">>>> ", "idBookshelf = ${idBookshelf}")
//        LogUtils.e(">>>> ", "AppConfig.bookGroupStyle = ${AppConfig.bookGroupStyle}")
//        if (id == idBookshelf) {
////            return if (AppConfig.bookGroupStyle == 1) idBookshelf2 else idBookshelf1
//            return idBookshelf
//        }
//        return id
//    }
//

}